<!--
 * @Descripttion: 商品选择
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-18 09:21:43
 * @LastEditors  : cxguo
 * @LastEditTime : 2019-12-26 17:44:27
 -->
<template>
  <div>
    <!-- {{ tableData }}<br>
    <el-button type="primary" @click="btnTestAdd">增加</el-button>
    <el-button type="primary" @click="btnTestDel">删除</el-button>
    <el-button type="primary" @click="btnTestUpdate">修改</el-button>
    <el-button type="primary" @click="btnTestGetData">获取值</el-button> -->
    <vxe-grid
      ref="table"
      class="grid"
      border
      size="small"
      resizable
      highlight-hover-row
      :optimization="{rHeights:{small:10}}"
      show-footer
      :footer-method="footerMethod"
      :footer-row-class-name="footerRowClassName"
      :edit-config="{showStatus:true, trigger: 'click', mode: 'row', activeMethod: activeRowMethod}"
      :columns="columnsData"
      :data="tableData"
      :edit-rules="validRules"
      @edit-closed="onEditClosed"
      @cell-mouseenter="onCellMouseEnter"
      @cell-mouseleave="onCellMouseLeave"
    />
  </div>
</template>
<script>
import { columns, tableApi, exportApi } from './mixins'
import { column2emptyObj, sunTableAmount } from '@/libs/util.js'
import GoodsList from './select'
import SimpleSelectGoods from './simple-select'
import { EMIT_METHODS } from '@/views/utils/config.js'
import { tableIndex } from '@/libs/mixins'

const TABLE_ID = 'goodselect'
const BLANK_DATA_LEN = 6

export default {
  name: 'GoodsSelected',
  mixins: [columns, tableApi, exportApi, tableIndex],
  data() {
    return {
      tableComp: null,
      tableData: [],
      columnsOrderData: null,
      simpleIframe: null,
      dialogVisible: true,
      validRules: {
        name: [{ required: true, message: '商品名称必填' }],
        code: [{ required: true, message: '商品编号必填' }],
        quantity: [{ required: true, message: '商品数量必填' }],
        unit: [{ required: true, message: '单位必填' }],
        price: [{ required: true, message: '单价必填' }],
        total: [{ required: true, message: '金额必填' }]
      }
    }
  },
  computed: {
    columnsData: function() {
      const columnsOrderData = this.columnsOrderData
      const originColumnsData = this.originColumnsData
      return this.getShowColumnsData(columnsOrderData, originColumnsData)
    },
    totalMsg: function() {
      const tableData = this.getTableData().tableData
      const data = {
        num: sunTableAmount(tableData, 'quantity'),
        price: sunTableAmount(tableData, 'total')
      }
      return data
    }
  },
  watch: {
    tableData: {
      handler(data) {
        console.log('watch - tableData')
        this.$refs.table.updateFooter()
        this.updateTableTotalAmount()
      },
      deep: true
    }
  },
  created() {
    this.initData()
  },
  mounted() {
    this.tableComp = this.$refs.table
    this.addTableBlankData(BLANK_DATA_LEN)
  },
  methods: {
    btnTestUpdate() {
      const tableData = this.$refs.table.getTableData().fullData
      this.updateTableData(tableData[0], { code: '3232', name: '失误失误' })
    },
    btnTestAdd() {
      const data = column2emptyObj(this.originColumnsData)
      this.addTableData([data])
    },
    btnTestDel() {

    },
    btnTestGetData() {
      const getRecordset = this.getRecordset()
      const getTableData = this.getTableData()
      console.log('getRecordset:', getRecordset)
      console.log('getTableData:', getTableData)
    },
    btnSteup() {
      const that = this
      const tableId = TABLE_ID
      const tableComp = this.$refs.table
      const columnsData = this.originColumnsData
      const instance = this.createSetColsDialog({ tableId, columnsData })
      instance.$on('on-col-orderdata-sure', function(data) {
        that.initTableCacheColData({ tableId, tableComp })
      })
    },
    closeModal(done) {
      this.dialogVisible = false
      done()
    },
    btnAddTableData() {
      const data = column2emptyObj(this.columnsData)
      this.addTableData([data])
    },
    btnRemoveTableData(row) {
      if (this.getTableData().tableData.length <= 1) return
      this.delTableData([row])
    },
    btnChooseGoods(params) {
      const iframe = this.popIframe()
      this.$bus.$on('on-goods-select-sure', ({ data, isClose }) => {
        this.handleTableData(this.formatSelectGoodsData(data))
        if (isClose) iframe.close()
      })
    },
    // api
    initData() {
      this.initCacheColData()
    },
    initCacheColData() {
      // const tableId = TABLE_ID
      // const tableComp = this.$refs.table
      // this.initTableCacheColData({ tableId, tableComp })
    },
    popIframe() {
      return this.$layer.iframe.addSingle({
        title: '选择商品',
        area: ['80%', '580px'],
        name: 'iframe-goods',
        content: {
          content: GoodsList,
          props: {
            oper: 'select'
          }
        }
      })
    },
    getValueByLabel(label, obj) {
      const keys = Object.keys(obj)
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i]
        if (key === label) {
          return obj[key]
        }
      }
      return null
    },
    getGoodsTotal(goodObj) {
      if (!goodObj.price || !goodObj.quantity) return '0.00'
      const quantity = goodObj.quantity || 0
      const price = goodObj.price
      const total = this.$amount(price).multiply(quantity).format()
      return total
    },
    formatSelectGoodsData(data) {
      data.forEach(element => {
        element._sure = true
        element._price = element.price
        element.quantity = element.num
        element.options = {}
        element.remark = ''
        element.price = null
      })
      return data
    },
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['quantity', 'total'].includes(column.property)) {
            return sunTableAmount(data, column.property)
          }
          return null
        })
      ]
    },
    /**
     * 更新table总价
     */
    updateTableTotalAmount() {
      const tableData = this.getTableData().fullData
      tableData.forEach(element => {
        let total = ''
        if (!element.price || !element.quantity) {
          total = '0.00'
        } else {
          total = this.getGoodsTotal(element)
        }
        element._sure && this.$set(element, 'total', total)
      })
    },
    handleTableData(data) {
      const tableData = this.tableData
      // 空位置数据
      const blankData = tableData.filter(item => { return !item._sure }) || []
      const blankDataLength = blankData.length
      const needLength = data.length + 1
      const addNumber = needLength - blankDataLength
      if (addNumber > 0) {
        this.addTableBlankData(addNumber)
      }
    },
    addTableBlankData(number) {
      const result = []
      for (let i = 0; i < number; i++) {
        const data = column2emptyObj(this.originColumnsData)
        result.push(data)
      }
      this.tableData.push(...result)
    },
    activeRowMethod(params) {
      const { row } = params
      return !row._sure
    },
    footerRowClassName() {
      return 'bg-gay'
    },
    popGoodSimpleSelect({ container, value }) {
      const iframe = this.$layer.iframe.addSingle({
        title: '',
        area: ['800px', 'auto'],
        position: ['0', '30px'],
        name: 'iframe-simple-goods',
        container,
        content: {
          content: SimpleSelectGoods,
          props: {
            keywords: value
          }
        }
      })
      return iframe
    },
    // ON
    onEditClosed(params) {
      this.closeSimpleGoodSelect()
    },
    closeSimpleGoodSelect() {
      const iframe = this.simpleIframe
      if (iframe) {
        iframe.close()
        this.simpleIframe = null
      }
    },
    onGoodsNameInput(e, params) {
      const container = e.target.parentNode
      const value = e.target.value
      const { row } = params
      if (!this.simpleIframe) this.simpleIframe = this.popGoodSimpleSelect({ container, value })
      else {
        const simpleGoodSelect = this.simpleIframe.iframeContent
        simpleGoodSelect && simpleGoodSelect.searchGoods(value)
      }
      this.$bus.$on(EMIT_METHODS.simpleGoodSelect, (targetData) => {
        targetData = this.formatSelectGoodsData([targetData])[0]
        this.$delete(targetData, '_XID')
        this.initUnitOptions(targetData)
        this.updateTableData(row, targetData)
        this.setTableActiveCell(targetData, 'num')
        this.closeSimpleGoodSelect()
      })
    },
    /**
     * 鼠标移入事件
     * @param {*} param0
     */
    onCellMouseEnter(params) {
      const { row, column } = params
      if (!row._sure) {
        this.setTableActiveRow(row)
      } else {
        this.setTableActiveCell(row, column.property)
      }
      this.currentRowIndex = row._XID
    },
    onCellMouseLeave() {
      this.currentRowIndex = null
    }
  }
}
</script>
<style lang="scss" scoped>
.grid{
  /deep/.el-icon-s-operation{
    font-size: 22px;
  }
  /deep/a.el-icon-s-operation:hover{
    font-size: 22px; color: #3198ff;
  }
  .table-oper {
    .el-button--mini{
      padding: 1px;
    }
  }
  /deep/.vxe-table{
    overflow: visible;
  }
  /deep/.vxe-table--body-wrapper.body--wrapper{
    overflow-x: visible;
    overflow-y: visible;
  }
  /deep/.el-input__inner{
    border: #ffffff solid 1px;
  }
  /deep/.el-input-number{
    .el-input__inner{
      border-color: #dcdfe6;
    }
  }
  /deep/.el-input__inner:focus{
    border: #409EFF solid 1px;
  }
  .btn-group{
    .el-button+.el-button{ margin-left: 5px; }
  }
}
</style>
